import axios from 'axios';
import {registry} from "@web/core/registry";
import {App, xml} from "@odoo/owl";
import {templates} from "@web/core/assets";


export const xml_register = []


const url = "/templates.html"

async function LoadFile(url) {

    const res = await fetch(url,)
    return await res.text()
}

let templates_value = await LoadFile(url);

export async function loadLocalTemplates() {

    const index = templates_value.indexOf('<template')
    templates_value = templates_value.slice(index)
    const doc = new DOMParser().parseFromString(templates_value, "text/xml");
    const nodesWithCustomAttr = doc.querySelectorAll('t');
    for (let i = 0; i < nodesWithCustomAttr.length; i++) {
        const node = nodesWithCustomAttr[i];
        // 检查节点是否有 'customAttr' 属性
        if (node.hasAttribute('t-name')) {
            templates.documentElement.appendChild(node.cloneNode(true));
            // console.log(`Node text: ${node.textContent}, customAttr: ${node.getAttribute('customAttr')}`);
        }
    }
}


export async function loadServerTemplates() {
    const tmpls = localStorage.getItem('serverTemplates')
    let result = null

    if (tmpls) {
        result = JSON.parse(tmpls)

    } else {
        let res = await axios.get('/web/myassets/any/web.assets_web.js')
        result = res.data.templates
        localStorage.setItem('serverTemplates', JSON.stringify(result))
    }


    for (const value of result) {

        const doc = new DOMParser().parseFromString('<templates>\n' + value + '</templates>\n', "text/xml");
        const nodesWithCustomAttr = doc.querySelectorAll('t');


        for (let i = 0; i < nodesWithCustomAttr.length; i++) {
            const node = nodesWithCustomAttr[i];
            // console.log(node.getInnerHTML());

            // 检查节点是否有 'customAttr' 属性
            if (node.hasAttribute('t-name')) {
                templates.documentElement.appendChild(node.cloneNode(true));
            }
        }
    }
}